package lyc.springcloud.admin.service.impl.systemManagerServiceImpl;

import lyc.springcloud.admin.dao.systemManagerDao.UserManagerDao;
import lyc.springcloud.admin.dto.systemManagerDto.UserManagerDto;
import lyc.springcloud.admin.service.def.systemManagerService.UserManagerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class UserManagerServiceImpl implements UserManagerService {
    @Autowired
    private UserManagerDao userManagerDao;

    /**
     * 查询所有启用的角色
     * */
    @Override
    public List<Map> selectAllEnableRoles() {
        return userManagerDao.selectAllEnableRoles();
    }

    /**
     * 用户管理---新增
     * */
    @Override
    public void userMng_insert(UserManagerDto params) {
        // 插入user表
        String userId = UUID.randomUUID().toString().replaceAll("-", "");
        params.setUserId(userId);
        userManagerDao.userMng_insert(params);
        // 插入user_role关联关系表
        String[] roleIds = params.getRoleIds().split(",");
        List<Map> list = new ArrayList<>();
        for (String id : roleIds) {
            Map map = new HashMap();
            map.put("userId", userId);
            map.put("roleId", id);
            list.add(map);
        }
        userManagerDao.user_role_insert(list);
    }

    /**
     * 用户管理---查询
     * */
    @Override
    public Map<String, Object> userMng_select(UserManagerDto params) {
        params.setPageNum((params.getPageNum()-1) * params.getPageSize());
        Map<String, Object> map = new HashMap<>();
        map.put("list",userManagerDao.userMng_select(params));
        map.put("total", userManagerDao.userMng_select_count());
        return map;
    }

    /**
     * 用户管理---编辑
     * */
    @Override
    public void userMng_update(UserManagerDto params) {
        // 更新user表数据
        userManagerDao.userMng_update(params);

        // 先全删当前userId相关的user_role行（根据userId删除user_role）
        String userId = params.getUserId();
        userManagerDao.deleteUserRoleRelationByUserId(userId);
        // 新增user_role关联关系
        String[] roleIds = params.getRoleIds().split(",");
        List<Map> list = new ArrayList<>();
        for (String id : roleIds) {
            Map map = new HashMap();
            map.put("userId", userId);
            map.put("roleId", id);
            list.add(map);
        }
        userManagerDao.user_role_insert(list);

    }

    /**
     * 用户管理---删除
     * */
    @Override
    public void userMng_delete(String params) {
        // 逻辑删除user表
        List<String> userIdList = Arrays.asList(params.split(","));
        userManagerDao.userMng_delete(userIdList);
        // 物理删除user_role关联关系表
        userManagerDao.user_role_delete(userIdList);
    }
}
